package com.example.sunmiv1.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.GoodWarehousingAdapter;
import com.example.sunmiv1.entity.GoodWarehousingInfo;
import com.example.sunmiv1.entity.StoreWarehousingInfo;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 入庫單
 * */
public class GoodWarehousingActivity extends Activity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.edit_goodWarehousing)
    EditText editGoodWarehousing;
    @BindView(R.id.tvSearch_goodWarehousing)
    TextView tvSearchGoodWarehousing;
    @BindView(R.id.listView_goodWarehousing)
    PullToRefreshListView listViewGoodWarehousing;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;

    private static final int DETAIL = 0;
    private static final int IN_WAREHOUSE = 1;

    private Context context;
    private int page = 1;
    private ACache aCache;
    private LoadingDialog loadingDialog;
    private GoodWarehousingInfo goodWarehousingInfo;
    private List<GoodWarehousingInfo.DataBean> list = new ArrayList<>();
    private GoodWarehousingAdapter warehousingAdapter;
    private Intent intent;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    for (GoodWarehousingInfo.DataBean dataBean : goodWarehousingInfo.getData()) {
                        list.add(dataBean);
                    }
                    page++;
                    setWarehousingAdapter();
                    break;
                case 2:
                    setWarehousingAdapter();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_good_warehousing);
        ButterKnife.bind(this);
        titleTitle.setText(R.string.goodWarehousingTitle);
        context = this;
        aCache = ACache.get(context);
        loadingDialog = new LoadingDialog(context);
        setWarehousingAdapter();
        getOrderList();
        initListener();
    }

    private void initListener() {
        listViewGoodWarehousing.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                list.clear();
                getOrderList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getOrderList();
            }
        });
        warehousingAdapter.setmClickListener((v, index) -> {
            switch (v.getId()) {
                case R.id.detail_goodWarehousing: //  調撥詳情
                    intent = new Intent(context, WarehousingDetailActivity.class);
                    intent.putExtra("id", list.get(index).getId());
                    intent.putExtra("status", "1");
                    intent.putExtra("type", list.get(index).getType());
                    intent.putExtra("remark", list.get(index).getRemarks());
                    startActivityForResult(intent, DETAIL);
                    break;
                case R.id.wareDetail_goodWarehousing://  入庫詳情
                    intent = new Intent(context, WarehousingDetailActivity.class);
                    intent.putExtra("id", list.get(index).getId());
                    intent.putExtra("type", list.get(index).getType());
                    intent.putExtra("status", "2");
                    intent.putExtra("remark", list.get(index).getRemarks());
                    startActivityForResult(intent, DETAIL);
                    break;
                case R.id.add_goodWarehousing: // 入庫
                    intent = new Intent(context, WarehousingActivity.class);
                    intent.putExtra("id", list.get(index).getId());
                    intent.putExtra("type", list.get(index).getType());
                    intent.putExtra("remark", list.get(index).getRemarks());
                    intent.putExtra("orderNo", list.get(index).getOrder_number());
                    startActivityForResult(intent, IN_WAREHOUSE);
                    break;
                case R.id.refuse_goodWarehousing://直接拒收
                    GoodWarehousingInfo.DataBean d = list.get(index);
                    refuseWarehousing(index);
                    break;
                case R.id.refuseDetail_goodWarehousing://拒收詳情
                    intent = new Intent(context, RefuseDetailActivity.class);
                    intent.putExtra("flag", 1);
                    intent.putExtra("stock_out_id", list.get(index).getStock_out_id());
                    intent.putExtra("type", list.get(index).getType());
                    startActivity(intent);
                    break;

            }
        });
    }

    @OnClick({R.id.title_back, R.id.btn_to_top, R.id.tv_start_time, R.id.tv_end_time, R.id.tvSearch_goodWarehousing,
            R.id.goodWarehousing_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.tv_start_time:
                Tools.getDateFromDatePickerDialog(tvStartTime);
                getOrderList();
                break;
            case R.id.tv_end_time:
                Tools.getDateFromDatePickerDialog(tvEndTime);
                getOrderList();
                break;
            case R.id.tvSearch_goodWarehousing:
                page = 1;
                list.clear();
                setWarehousingAdapter();
                getOrderList();
                break;
            case R.id.btn_to_top:
                listViewGoodWarehousing.getRefreshableView().setSelection(0);
                break;
            case R.id.goodWarehousing_code:
                startQrCode();
                break;
        }
    }

    // 開始掃碼
    private void startQrCode() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申請權限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 二維碼掃碼
        Intent intent = new Intent(context, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    private void setWarehousingAdapter() {
        if (warehousingAdapter == null) {
            warehousingAdapter = new GoodWarehousingAdapter(context, list);
            listViewGoodWarehousing.setAdapter(warehousingAdapter);
        } else {
            warehousingAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (requestCode) {
                case DETAIL:
                    break;
                case IN_WAREHOUSE:
                    if (resultCode == 1) {
                        page = 1;
                        list.clear();
                        getOrderList();
                    }
                    break;
                case Constant.REQ_QR_CODE:
                    Bundle bundle = data.getExtras();
                    page = 1;
                    list.clear();
                    setWarehousingAdapter();
                    editGoodWarehousing.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
                    getOrderList();
                    break;
                default:
                    break;
            }
        }
    }

    private void refuseWarehousing(int index) {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("warehousing_id", list.get(index).getId());
            jsonObject.put("stock_out_id", list.get(index).getStock_out_id());
            jsonObject.put("type", list.get(index).getType());
            jsonObject.put("user_type", aCache.getAsString("userType"));
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.STORE_REFUSE_WAREHOUSING, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        JSONObject json = new JSONObject(text);
                        Toast.makeText(context, json.getString("message"), Toast.LENGTH_SHORT).show();
                        if (json.getInt("status") == 1) {
                            getWarehousingDetail(index);
                        } else {
                            loadingDialog.dismiss();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private StoreWarehousingInfo storeWarehousingInfo;

    private void getWarehousingDetail(int index) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("id", list.get(index).getWarehouse_id());
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.GET_STORE_WAREHOUSING_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    storeWarehousingInfo = GsonUtils.JsonToBean(text, StoreWarehousingInfo.class);
                    if (storeWarehousingInfo.getStatus() == 1) {
                        list.set(index,new GoodWarehousingInfo.DataBean(storeWarehousingInfo.getData().getInfo()));
                    }
                    setWarehousingAdapter();
                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getOrderList() {
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("start_time", tvStartTime.getText().toString().trim());
            jsonObject.put("end_time", tvEndTime.getText().toString().trim());
            jsonObject.put("order_number", editGoodWarehousing.getText().toString().trim());
            jsonObject.put("page", page);
            jsonObject.put("limit", 20);
            HttpUtils.post(context, Common.GET_ENTER_ORDER_LIST, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    listViewGoodWarehousing.onRefreshComplete();
                    goodWarehousingInfo = GsonUtils.JsonToBean(text, GoodWarehousingInfo.class);
                    Message msg = new Message();
                    if (goodWarehousingInfo.getStatus() == 1) {
                        msg.what = 1;
                    } else {
                        msg.what = 2;
                    }
                    handler.sendMessage(msg);
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                    listViewGoodWarehousing.onRefreshComplete();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否則所有的組件都不會有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);

    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 點擊的是輸入框區域，保留點擊EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

}
